import Server from "./Server";
import Mqtt from './Mqtt'
import config from './config'
import Koa  from 'koa'
import bodyParser from 'koa-bodyparser';

import redis, { RedisClient } from 'redis'
let redisClient:RedisClient

const server = new Server({port : config.server.port})

const mqtt = new Mqtt({host : config.mqtt.host, port : config.mqtt.port, username : config.mqtt.username, password : config.mqtt.password})
mqtt.on('connect', () => {
    console.log('mqtt连接成功')
    mqtt.subscribe(config.mqtt.subscribe)


    server.on<DataType>('data', data => {
        const cmd = data.cmd
        //console.log({cmd : cmd, packDir : data.packDir, type : data.type, timestamp : data.timestamp, deviceId : data.deviceId, data : data.data})
        if(cmd == '0008' || cmd == '0005') { //发起充电，增加充电，结束充电，结束充电后订单上报
            redisClient.rpush(config.chargeOrderMessageList, JSON.stringify({cmd, timestamp : data.timestamp, data : data.data, type : data.type}))
        }
        
        mqtt.publish(config.mqtt.deviceReportMsgTopic, JSON.stringify({cmd : cmd, packDir : data.packDir, type : data.type, timestamp : data.timestamp, deviceId : data.deviceId, data : data.data}))
        
    }).on('destroy', (deviceId:string) => {
        mqtt.publish(config.mqtt.deviceReportMsgTopic, JSON.stringify({cmd : '0000', deviceId, timestamp : (new Date()).getTime()}))
    })
    .on('start', () => {
        console.log('server启动成功')

        //web服务
        const webApp = new Koa();
        webApp.use(bodyParser());
        webApp.use(ctx => {
            if(ctx.request.method === 'POST') {
                const path = ctx.request.path
                const body:any = ctx.request.body
                if(path === config.web.sendPath) {
                    server.send(body.deviceId, body.data)
                    ctx.body = 'OK'
                }else if(path === config.web.onlinePath) {
                    const sock = server.getSock(body.deviceId)
                    ctx.body = sock ? sock.activeTime : 0
                }
                
            }
        })
        webApp.listen(config.web.port, () => {
            console.log('web启动成功')
        })
    
    })
    
    server.start()


}).on<{topic:string, message:Buffer}>('message', params => {
    let data = JSON.parse(params.message.toString())
    server.send(data.deviceId, data.body)
})


redisClient = redis.createClient({
    host : config.redis.host,
    port : config.redis.port,
    password : config.redis.password
})

mqtt.connect() //连接mqtt